#include "glogloging.h"
#include <glog/logging.h>
#include <string>
#include <map>
#include <sstream>
#include <fstream>
#include <filesystem>
#include <memory>

#include <boost/json/error.hpp>
#include <boost/json/parse_options.hpp>
#include <boost/json.hpp>
#include <iostream>
LogConfig* LogConfig::GetInstance()
{
    return pconfigins;
}
LogConfig::LogConfig(const std::string &configpath) : configpath_(configpath)
{
}

LogConfig::~LogConfig()
{
}

int LogConfig::ParseConfig()
{
    std::fstream fs;
    fs.open(configpath_.c_str(), std::ios_base::in);
    if (!fs.is_open())
    {
        return 1;
    }
    std::filesystem::path config(configpath_);
    auto filesize = std::filesystem::file_size(config);
    //sanitizer要求必须加1,否则地址检测会报错
    std::unique_ptr<char[]> pdata(new char[filesize + 1]);
    pdata[filesize] = '\0';
    fs.read(pdata.get(), filesize);
    boost::json::parse_options ps;
    ps.allow_comments = true;
    ps.allow_invalid_utf8 = true;
    boost::json::error_code er;
    auto val = boost::json::parse(pdata.get(), er, {}, ps);
    if (er.failed())
    {
        return 1;
    }
    auto jsonobj = val.as_object();
    for (auto q = jsonobj.begin(); q != jsonobj.end() ; ++q)
    {
        if(q->value().is_string())
        {
            std::string key= q->key();
            std::string val = q->value().as_string().c_str();
            configmap_.insert(std::make_pair(key,val));
        }
    }
    return 0;
}

std::string LogConfig::GetItem(const std::string &item)
{
    return configmap_[item];
}



LogConfig *LogConfig::pconfigins = new (std::nothrow) LogConfig("./glogconfig.json");
GlogLogger *GlogLogger::pins = new (std::nothrow) GlogLogger(LogConfig::GetInstance());



GlogLogger* GlogLogger::GetInstance()
{
    return pins;
}

void GlogLogger::Write(int mod ,int level ,const char* log) const
{
    LOG(INFO)<<log;
}
GlogLogger::GlogLogger(LogConfig *conf)
{
    std::stringstream ss;
    int res = conf->ParseConfig();
    if (res == 0)
    {
        std::string progname = conf->GetItem("progname");
        google::InitGoogleLogging(progname.c_str());
        //std::string logpathtrace = conf->GetItem("logpathtrace");
        //std::string logpathdebug = conf->GetItem("logpathdebug");
        std::string logpathinfo = conf->GetItem("logpathinfo");
        //std::string logpathwarn = conf->GetItem("logpathwarn");
        //std::string logpatherror = conf->GetItem("logpatherror");
        //std::string logpathfatal = conf->GetItem("logpathfatal");
        //google::SetLogDestination(google::glog_, logpathtrace.c_str());
        //google::SetLogDestination(DEBUG, logpathdebug.c_str());
        google::SetLogDestination(google::GLOG_INFO, logpathinfo.c_str());
        //google::SetLogDestination(WARN, logpathwarn.c_str());
        //google::SetLogDestination(ERROR, logpatherror.c_str());
        //google::SetLogDestination(FATAL, logpathfatal.c_str());
    }
}


GlogLogger::~GlogLogger()
{
    google::ShutdownGoogleLogging();
}
